package com.eve.springcloud.controller;

import java.net.URI;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.eve.common.util.Jsons;
import com.eve.springcloud.lb.LoadBalancer;

@RestController
public class DeptController {
    
	@Resource
	private RestTemplate restTemplate;
	/**
	 * 引入自定义的手写Ribbon算法
	 */
	@Resource
	private LoadBalancer loadBalance;
	@Resource
	private DiscoveryClient discovery;
	/**
	 * 请求地址:单机版
	 */
//	public static final String URL = "http://localhost:8001/";
	/**
	 * Eureka版：在Eureka中注册的名称，需要在RestTemplate中添加负载均衡支持
	 */
	public static final String URL = "http://CLOUD-PAYMENT-SERVICE/";
	
	@RequestMapping(value = "/dept/find/{deptId}")
	public @ResponseBody Jsons find(@PathVariable("deptId") Long deptId) {
		Jsons get = restTemplate.getForObject(URL + "dept/find/" + deptId, Jsons.class);
		return get;
	}
	
	/**
	 * 发现当前服务中的LB手写Ribbon轮询算法
	 * @return
	 */
	@RequestMapping(value = "/dept/get/lb")
	public @ResponseBody String discovery() {
		// 具体应用有哪些实例
		List<ServiceInstance> instances = discovery.getInstances("CLOUD-PAYMENT-SERVICE");
		if(instances == null || instances.size() <= 0) {
			return null;
		}
		ServiceInstance lbInstance = loadBalance.instance(instances);
		URI uri = lbInstance.getUri();
		// 需要请求的接口
		return restTemplate.getForObject(uri + "/get/lb", String.class);
	}
	/**
	 * Sleuth+Zipkin 20200527
	 * @return
	 */
	@RequestMapping(value = "/dept/zipkin")
	public @ResponseBody String getZipkin() {
		String get = restTemplate.getForObject(URL + "dept/zipkin/", String.class);
		return get;
	}
	
}
